package com.cn.controller;


import com.cn.po.*;
import com.cn.service.WangLuWordService;
import com.cn.vo.ErrorWordVo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/errorWord")
public class ErrorWordController {
    @Autowired
    WangLuWordService wangLuWordService;

    // 错误单词显示界面分页显示错误单词
    @GetMapping("/all")
    public Result getErrorWords(@RequestParam("page") int page, @RequestParam("size") int pageSize) {
        System.out.println("你好，错误单词");
        List<WordWL> errorWords = wangLuWordService.getPaginatedErrorWords(page, pageSize);
        int errorWordsCount = wangLuWordService.getErrorWordsCount();
        ErrorWordVo errorWordVo = new ErrorWordVo(errorWordsCount,errorWords);
        // response.data would output the entire JSON object returned by the server.
        //response.data 就是 Result
        return new Result(Code.GET_OK,errorWordVo,"");
    }


    // 获取指定章节的错误单词
    @GetMapping("/specifiedChapterWords")
    public Result getErrorWordsByChapter(@RequestParam("chapter") String chapter){
        System.out.println("zhuzhu1");
        List<WordWL> words = wangLuWordService.getErrorWordsByChapter(chapter);
        System.out.println(words.size());
        for (WordWL word : words) {
            System.out.println(word);
        }
        return new Result(200,words,"");
    }


    //获取 current_error_count >= 1 的单词的章节
    @GetMapping("/errorChapters")
    public Result getErrorChapters(){
        List<WordWL> errorWords = wangLuWordService.getWordsWithErrors();
        // 按照顶层章节分组，如第3章，4章等
        Map<String, Set<String>> chapterGroups = errorWords.stream()
                .collect(Collectors.groupingBy(
                        word -> word.getWangLuChapter().split("\\.")[0], // 获取章节的第一部分
                        Collectors.mapping(WordWL::getWangLuChapter, Collectors.toSet()) // 去重每个章节
                ));
        return new Result(200, chapterGroups, "获取错误章节成功");
    }


    //在后端添加 /errorWord/test/error-submit 接口来处理错误测试的提交逻辑。
    @PostMapping("/test/submit")
    public Result submitErrorTest(@RequestBody FrontPojo payload) {
        List<TestWord> userAnswers = payload.getAnswers();
        ArrayList<Map<String, Object>> result = new ArrayList<>();
        ArrayList<Integer> correctWordIds = new ArrayList<>();
        ArrayList<Integer> incorrectWordIds = new ArrayList<>();

        for (TestWord userAnswer : userAnswers) {
            Integer wordId = userAnswer.getWordId();
            String answerWord = userAnswer.getUserAnswer();
            WordWL word = wangLuWordService.getWordById(wordId);

            Map<String, Object> wordResult = new HashMap<>();
            wordResult.put("id", word.getId());
            wordResult.put("word", word.getWord());
            wordResult.put("usPhonetic", word.getUsPhonetic());
            wordResult.put("usVoice", word.getUsVoice());
            wordResult.put("ukPhonetic", word.getUkPhonetic());
            wordResult.put("ukVoice", word.getUkVoice());
            wordResult.put("wangLuMeaning", word.getWangLuMeaning());
            wordResult.put("userAnswer", answerWord);
            boolean isCorrect = answerWord.equalsIgnoreCase(word.getWord());
            wordResult.put("isCorrect", isCorrect);

            if (isCorrect) {
                correctWordIds.add(wordId);
            } else {
                incorrectWordIds.add(wordId);
            }
            result.add(wordResult);
        }

        // 更新错误次数,正确单词和错误单词都要更新
        wangLuWordService.updateErrorAndCorrectCounts(incorrectWordIds,correctWordIds);



        return new Result(200, result, "测试结果");
    }

    @GetMapping("/exportAllWordsToExcel")
    public void exportErrorWordsToExcel(HttpServletResponse response) {
        System.out.println("导出单词");
        try {
            // 获取所有错误单词
            List<WordWL> errorWords = wangLuWordService.getWordsWithErrors();
            System.out.println(errorWords);

            // 创建 Excel 工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("错误单词列表");

            // 设置表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"单词", "英式音标", "美式音标", "中文意思", "错误次数"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            for (int i = 0; i < errorWords.size(); i++) {
                WordWL word = errorWords.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(word.getWord());
                row.createCell(1).setCellValue(word.getUkPhonetic());
                row.createCell(2).setCellValue(word.getUsPhonetic());
                row.createCell(3).setCellValue(word.getWangLuMeaning());
                row.createCell(4).setCellValue(word.getErrorCount());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=error_words.xlsx");

            // 写入响应输出流
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
